from django.core.validators import FileExtensionValidator
from rest_framework import serializers


class UploadImageSerializer(serializers.Serializer):
    # ImageField: 会校验上传的文件是否是图片
    image = serializers.ImageField(
        validators=[FileExtensionValidator(allowed_extensions=['png', 'jpg', 'jpeg', 'gif'])],
        error_messages={'required': '请上传图片！',
                        'invalid_image': '请上传正确格式的图片, 格式必须是 png, jpg, jpeg, gif'}

    )

    def validate_image(self, value):
        max_size = 2 * 1024 * 1024
        size = value.size
        if size > max_size:
            raise serializers.ValidationError('图片最大不能超过2M')
        return value
